<?php
class categories{
	public function getAllCates($data = array()){
		if (empty($data)){
			$data = $this -> getCates();
		}
		$cates = array();
		if (!empty($data)){
			foreach($data as $v){
				$cates[$v['parent_id']*1][$v['cat_id']*1] = $v;
			}
		}
		return $cates;
	}

	public function getCates(){
		$sql = 'SELECT cat_id, cat_name, parent_id FROM '.DB_PRE.DB_PRE_ECSHOP.'category ORDER BY sort_order DESC, cat_id DESC';
		$data = diy_execute($sql);
		$r = array();
		if (!empty($data)){
			foreach($data as $v){
				$r[$v['cat_id']] = $v;
			}
		}
		return $r;
	}


	public function getTopNavCatesMenus($data = false){
		if ($data === false){
			$data = $this -> ExtTreeData($this -> getAllCates());
		}
		$r = '';
		#print_r($data);
		if (!empty($data)){
			$r = '<ul class="dropdown-menu">';
			foreach($data as $v){
				if (isset($v['sub']) && !empty($v['sub'])){
					$r .= '<li class="dropdown-submenu">';
					$r .= '<a tabindex="-1" href="'.makeUrl("products", "cateId=".$v["cat_id"]).'">'.trim($v["cat_name"]).'</a>';
					$r .= $this -> getTopNavCatesMenus($v['sub']);
					$r .= '</li>';
				} else {
					$r .= '<li><a href="'.makeUrl("products", "cateId=".$v["cat_id"]).'">'.trim($v["cat_name"]).'</a></li>';
				}
			}
			$data = end($data);
			if ($data['parent_id']*1 == 0){
				$r .= '<li class="divider"></li>';
				$r .= '<li><a href="'.makeUrl('products').'">查看所有产品</a></li>';
			}
			$r .= '</ul>';
		}
		return $r;
	}

	public function ExtTreeData($data,$start=0){
		$r = array();
		if(isset($data[$start]) && !empty($data[$start])){
			foreach ($data[$start] as $k=>$v){
				$r[$k] = $v;
				if(isset($data[$k]) && !empty($data[$k])){
					$r[$k]['sub'] = $this -> ExtTreeData($data, $k);
				}
			}
		}
		return $r;
	}


	public function ExtTreeData2($data,$start=0, $parentInfo=array()){
		static $r = array();
		if(isset($data[$start]) && !empty($data[$start])){
			foreach ($data[$start] as $k=>$v){
				$r[$k] = array_merge($parentInfo, array($k => $v));
				if(isset($data[$k]) && !empty($data[$k])){
					$this -> ExtTreeData2($data, $k, $r[$k]);
				}
			}
		}
		return $r;
	}




}